package cn.edu.zjicm.wordsnet_d.BroadcastReceiver;

//这里可以控制是否需要启动service
import java.util.Calendar;
import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.activity.MainActivity;
import cn.edu.zjicm.wordsnet_d.activity.WelcomeActivity;
import cn.edu.zjicm.wordsnet_d.data.DataManager;
import cn.edu.zjicm.wordsnet_d.data.OneWord;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.db.WordFactory;
import cn.edu.zjicm.wordsnet_d.util.LogUtil;

public class AlarmReceiver extends BroadcastReceiver {

	public static final int ADD_MODE = 0; // 初始设置模式
	public static final int CHECK_MODE = 1; // 检查学习模式
	public static final int UPDATE_MODE = 2; // 更新学习模式
	public static final int NOTIFICATION_ID = 10;

	@Override
	public void onReceive(Context context, Intent intent) {
		int mode = intent.getIntExtra("mode", 0);
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(System.currentTimeMillis());
		if (mode == CHECK_MODE) {
			notifyStudy(context);
		}
	}

	public static NotificationManager mNotificationManager;

	// 通知栏中加入学习提醒
	public void notifyStudy(Context context) {
		if (!AppPreference.isStudyNotification(context))
			return;

		if (AppPreference.hasStudyingBook(context))
			DataManager.getInstance().doStudyProgress(context); // 推送单词
		// DataManager.getInstance().setTodayStudyPlan(context); //设置当天学习计划

		// 预定下一次提醒
		alarmCheckStudy(context);

		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(System.currentTimeMillis());
		int hour = c.get(Calendar.HOUR_OF_DAY);
		int minute = c.get(Calendar.MINUTE);
		if (!(hour >= 8 && hour <= 22)) // 8到22点间有学习提醒，否则不发学习提醒
			return;

		if (hour == 22 && minute > 0) // 只到22点，超过就不发学习提醒
			return;

		// 如果软件可见，
		if (isTopActivity(context)) {
			cancleNotifyStudy(context);
			return;
		}

		int num = WordFactory.getInstance(context).getNumberOfWordsForTestOfDegree(OneWord.DEGREE_UNFAMILIAR);
		if (num <= 0) {
			return;
		}

		// 创建一个NotificationManager的引用
		mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

		// 定义Notification的各种属性
		int icon = R.drawable.logo; // 通知图标
		CharSequence contentTitle = "您有" + num + "个单词需要学习"; // 通知栏标题
		CharSequence contentText = "点击可以开始学习"; // 通知栏内容
		// 用上面的属性初始化 Nofification
		Notification notification = new Notification(icon, contentTitle, System.currentTimeMillis());

		// Intent notificationIntent = new Intent(context, MainActivity.class);
		// // 点击该通知后要跳转的Activity
		// Intent notificationIntent = new Intent(context,
		// ExamRunActivity.class);
		// notificationIntent.putExtra("familiar_degree",
		// OneWord.DEGREE_UNFAMILIAR);
		Intent notificationIntent = new Intent(context, MainActivity.class);
		notificationIntent.putExtra("start_mode", 1);
		// FLAG_ACTIVITY_CLEAR_TOP:如果在当前Task中，有要启动的Activity，那么把该Acitivity之前的所有Activity都关掉
		// FLAG_ACTIVITY_NEW_TASK:系统会检查当前所有已创建的Task中是否有该要启动的Activity的Task，若有，则在该Task上创建Activity，若没有则新建具有该Activity属性的Task，并在该新建的Task上创建Activity
		notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
		// pendingIntent:即将到来的意图，当前activity并不能马上启动它所包包含的intent，而是在外部执行pendingIntent时，调用intent的。
		PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
		notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
		String stringUri = AppPreference.getNotificationRing(context);
		if (!("null".equals(stringUri))) {
			if (null == stringUri) {
				String defaultNotificationRing = "android.resource://" + context.getPackageName() + "/" + R.raw.notify;
				notification.sound = Uri.parse(defaultNotificationRing);// 自定义声音
			} else {
				notification.sound = Uri.parse(AppPreference.getNotificationRing(context));// 自定义声音
			}
		}
		// notification.defaults = Notification.DEFAULT_ALL;//调用下面所有的
		// notification.defaults
		// |=Notification.DEFAULT_SOUND;//声音（调用默认声音，有这个上面的自定义声音就取消掉）

		// notification.defaults |= Notification.DEFAULT_SOUND;// 系统自带的通知声音
		notification.defaults |= Notification.DEFAULT_VIBRATE;// 振动
		notification.defaults |= Notification.DEFAULT_LIGHTS;// 提示灯
		notification.flags |= Notification.FLAG_AUTO_CANCEL;// 在通知栏按下后自动消失
		// notification.flags |= Notification.FLAG_ONGOING_EVENT;// 通知放置在正在运行
		mNotificationManager.notify(NOTIFICATION_ID, notification);// 把Notification传递给NotificationManager
	}

	/**
	 * 判断软件是否可见
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isTopActivity(Context context) {
		String packageName = "cn.edu.zjicm.wordsnet_d";
		String className = "cn.edu.zjicm.wordsnet_d.activity.LockActivity";
		ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> tInfos = activityManager.getRunningTasks(1);
		if (tInfos.size() > 0) {
			// LogActivity.addLog("包名:" +
			// tInfos.get(0).topActivity.getPackageName());
			// LogActivity.addLog("活动名:" +
			// tInfos.get(0).topActivity.getClassName());
			if (packageName.equals(tInfos.get(0).topActivity.getPackageName()) && !className.equals(tInfos.get(0).topActivity.getClassName())) {
				return true;
			}
		}
		return false;
	}

	// 取消学习提醒
	public static void cancleNotifyStudy(Context context) {
		NotificationManager mNotificationManager;
		mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		mNotificationManager.cancel(NOTIFICATION_ID);
	}

	// 定时检查是否有单词需要学习
	public static void alarmCheckStudy(Context context) {
		Intent intent = new Intent();
		intent.setAction("zjicm.edu.cn.alarmreceiver.action");
		intent.putExtra("mode", AlarmReceiver.CHECK_MODE);
		PendingIntent pi = PendingIntent.getBroadcast(context, AlarmReceiver.CHECK_MODE, intent, 0);

		AlarmManager am = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
		Calendar calendar = Calendar.getInstance();
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		System.out.println("hour=" + hour);
		long alarmTime = 0;

		// 8到22点间发学习提醒，否则不发学习提醒
		if (hour >= 6 && hour <= 20) {
			alarmTime = calendar.getTimeInMillis() + 2 * 60 * 60 * 1000;
		} else {
			alarmTime = calendar.getTimeInMillis() + (8 + 24 - hour) % 24 * 1 * 60 * 60 * 1000;
		}

		am.set(AlarmManager.RTC_WAKEUP, alarmTime, pi);

	}
}
